﻿using AVIS.OutBound.WizardAgent.Helpers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;

namespace AVIS.OutBound.WizardAgent
{
    public static class DTOExtension
    {
        /// <summary>
        /// 解析车辆基本信息
        /// </summary>
        /// <param name="carGroup"></param>
        /// <param name="VehicleElement"></param>
        public static void ParseVehicleXml(this CarGroupDto carGroup, XElement VehicleElement)
        {
            if (VehicleElement == null)
            {
                return;
            }

            var xVehMakeModel = XmlHelpler.FindXElement(VehicleElement, "VehMakeModel", WizardConsts.XNamespace);

            carGroup.ModelName = XmlHelpler.ParseValue(xVehMakeModel, "Name");
            carGroup.SIPPCode = XmlHelpler.ParseValue(xVehMakeModel, "Code");
            carGroup.PictureURL = XmlHelpler.ParseValue(XmlHelpler.FindXElement(VehicleElement, "PictureURL", WizardConsts.XNamespace));
        }

        /// <summary>
        /// 解析车组的总费用
        /// </summary>
        /// <param name="carGroup"></param>
        /// <param name="VehicleElement"></param>
        public static void ParseTotalChargeXml(this CarGroupDto carGroup, XElement TotalChargeElement)
        {
            // 预计总金额
            var strPrice = XmlHelpler.ParseValue(TotalChargeElement, "EstimatedTotalAmount");
            carGroup.Price = double.Parse(strPrice);
            carGroup.CurrencyCode = XmlHelpler.ParseValue(TotalChargeElement, "CurrencyCode");
        }

        /// <summary>
        /// 解析车组的租金
        /// </summary>
        /// <param name="RentalRateElement"></param>
        /// <param name="carGroup"></param>
        /// <param name="ns"></param>
        public static void ParseRentalRateXml(this CarGroupDto carGroup, XElement RentalRateElement)
        {
            if (RentalRateElement == null)
            {
                return;
            }

            var xRateDistance = XmlHelpler.FindXElement(RentalRateElement, "RateDistance", WizardConsts.XNamespace);
            var xVehicleCharges = XmlHelpler.FindXElement(RentalRateElement, "VehicleCharges", WizardConsts.XNamespace);
            var xRateQualifier = XmlHelpler.FindXElement(RentalRateElement, "RateQualifier", WizardConsts.XNamespace);

            // 套餐价格代码
            carGroup.RateCategory = XmlHelpler.ParseValue(xRateQualifier, "RateCategory");
            carGroup.RateCode = XmlHelpler.ParseValue(xRateQualifier, "RateQualifier");

            // 限制里程数
            var Unlimited = XmlHelpler.ParseValue(xRateDistance, "Unlimited");
            var Quantity = XmlHelpler.ParseValue(xRateDistance, "Quantity");
            var DistUnitName = XmlHelpler.ParseValue(xRateDistance, "DistUnitName");
            var VehiclePeriodUnitName = XmlHelpler.ParseValue(xRateDistance, "VehiclePeriodUnitName");
            if (Unlimited == "true")
            {
                carGroup.PriceInclue.Distance.Unlimited = true;
            }
            else
            {
                carGroup.PriceInclue.Distance.Unlimited = false;
                carGroup.PriceInclue.Distance.Quantity = Quantity;
                carGroup.PriceInclue.Distance.DistanceUnit = DistUnitName;
                carGroup.PriceInclue.Distance.PeriodUnit = VehiclePeriodUnitName;
            }

            // 收费价格说明
            foreach (var xCharge in xVehicleCharges.Elements(XNamespace.Get(WizardConsts.XNamespace) + "VehicleCharge"))
            {
                // 租期
                var xCalculation = XmlHelpler.FindXElement(xCharge, "Calculation", WizardConsts.XNamespace);
                if (xCalculation != null)
                {
                    carGroup.RentalLength = XmlHelpler.ParseValue(xCalculation, "Quantity");
                    carGroup.RentalUnit = XmlHelpler.ParseValue(xCalculation, "UnitName");
                }

                var IncludedInRate = XmlHelpler.ParseValue(xCharge, "IncludedInRate");
                var Purpose = XmlHelpler.ParseValue(xCharge, "Purpose");
                var Description = XmlHelpler.ParseValue(xCharge, "Description");
                if (IncludedInRate == "true" && Purpose != "1")
                {
                    carGroup.PriceInclue.VehicleCharges.Add(Description);
                }
                else if (IncludedInRate == "true" && Description.Contains("One way fee"))
                {
                    carGroup.PriceInclue.VehicleCharges.Add(Description);
                }
                else if (Description.Contains("Local Tax"))
                {
                    carGroup.PriceInclue.VehicleCharges.Add(Description);
                }
            }
        }

        /// <summary>
        /// 套餐价格包含的保险项目
        /// </summary>
        /// <param name="carGroup"></param>
        /// <param name="PricedCoveragesElement"></param>
        public static void ParsePricedCoveragesXml(this CarGroupDto carGroup, XElement PricedCoveragesElement)
        {
            if (PricedCoveragesElement == null)
                return;

            foreach (var xPricedCoverage in PricedCoveragesElement.Elements(XNamespace.Get(WizardConsts.XNamespace) + "PricedCoverage"))
            {
                var xCoverage = XmlHelpler.FindXElement(xPricedCoverage, "Coverage", WizardConsts.XNamespace);
                var xCharge = XmlHelpler.FindXElement(xPricedCoverage, "Charge", WizardConsts.XNamespace);
                if (XmlHelpler.ParseValue(xCharge, "IncludedInRate") == "true" && XmlHelpler.ParseValue(xCharge, "Amount") == "0.00")
                {
                    var strCode = XmlHelpler.ParseValue(xCoverage, "Code");
                    var strContent = XmlHelpler.ParseValue(XmlHelpler.FindXElement(xCoverage, "Details", WizardConsts.XNamespace));
                    if (!carGroup.PriceInclue.Coverages.Exists(c => c.Code == strCode))
                    {
                        carGroup.PriceInclue.Coverages.Add(new PriceIncludeCoverageDto { Code = strCode, Content = strContent });
                    }
                }

                // 处理保险的起赔金额
                if (XmlHelpler.ParseValue(xCharge, "Description") == "Insurance Excess" && XmlHelpler.ParseValue(xCharge, "Amount") != "0.00")
                {
                    var strCode = XmlHelpler.ParseValue(xCoverage, "Code");
                    var coverage = carGroup.PriceInclue.Coverages.FirstOrDefault(c => c.Code == strCode);
                    if (coverage != null)
                    {
                        double amount = 0;
                        if (double.TryParse(XmlHelpler.ParseValue(xCharge, "Amount"), out amount))
                        {
                            coverage.InsuranceExcessAmount = amount;
                        }

                        coverage.InsuranceExcessCurrencyCode = XmlHelpler.ParseValue(xCharge, "CurrencyCode");
                    }
                }
            }
        }

        /// <summary>
        /// 车辆功能特征（比如：自动挡、4座等）
        /// </summary>
        /// <param name="ReferenceElement"></param>
        /// <param name="carGroup"></param>
        public static void ParseFeaturesReferenceXml(this CarGroupDto carGroup, XElement ReferenceElement)
        {
            if (ReferenceElement == null)
            {
                return;
            }

            var ReferenceType = XmlHelpler.ParseValue(ReferenceElement, "Type");  // Features
            var ReferenceID = XmlHelpler.ParseValue(ReferenceElement, "ID");
            if (ReferenceType == "Features")
            {
                carGroup.Feature = new CarFeatureDto(ReferenceID);
            }
        }

        /// <summary>
        /// 车辆装备等增值服务（如：儿童座椅、(GPS) 导航仪等）
        /// </summary>
        /// <param name="carGroup"></param>
        /// <param name="PricedEquipsElement"></param>
        public static void ParsePricedEquipsXml(this CarGroupDto carGroup, XElement PricedEquipsElement)
        {
            /*******************  查询订单的XML 格式  *****************************************
             ** <PricedEquips>
             **	    <PricedEquip>
             **		    <Equipment EquipType="13" Quantity="1"/>
             **		    <Charge TaxInclusive="false" IncludedInRate="false" Amount="14.45" CurrencyCode="USD"/>
             **	    </PricedEquip>
             ** </PricedEquips>
             **************************************************************************/

            /*******************  增值服务的XML 格式  *****************************************
             ** <PricedEquips>
             **	    <PricedEquip>
             **	        <Equipment EquipType="9"/>
             **	        <Charge TaxInclusive="false" IncludedInRate="false" Amount="8.40" CurrencyCode="EUR">
             **	            <Calculation UnitCharge="8.40" UnitName="Daily"/>
             **	        </Charge>
             **	    </PricedEquip>
             **	</PricedEquips>
             **************************************************************************/

            if (PricedEquipsElement == null)
            {
                return;
            }

            foreach (var xEquip in PricedEquipsElement.Elements(XNamespace.Get(WizardConsts.XNamespace) + "PricedEquip"))
            {
                var xEquipment = XmlHelpler.FindXElement(xEquip, "Equipment", WizardConsts.XNamespace);
                var xCharge = XmlHelpler.FindXElement(xEquip, "Charge", WizardConsts.XNamespace);
                var xCharge_Calculation = XmlHelpler.FindXElement(xCharge, "Calculation", WizardConsts.XNamespace);
                string strQuantity = XmlHelpler.ParseValue(xEquipment, "Quantity");

                carGroup.CarEquipments.Add(new CarEquipmentDto
                {
                    Type = XmlHelpler.ParseValue(xEquipment, "EquipType"),
                    Quantity = string.IsNullOrEmpty(strQuantity) ? 0 : int.Parse(strQuantity),
                    Amount = XmlHelpler.ParseValue(xCharge, "Amount"),
                    CurrencyCode = XmlHelpler.ParseValue(xCharge, "CurrencyCode"),
                    UnitPrice = XmlHelpler.ParseValue(xCharge_Calculation, "UnitCharge"),
                    UnitName = XmlHelpler.ParseValue(xCharge_Calculation, "UnitName"),
                });
            }
        }

        /// <summary>
        /// 车辆功能特征（比如：自动挡、4座等）
        /// </summary>
        /// <param name="carGroup"></param>
        /// <param name="ReferenceElement"></param>
        /// <param name="xVehicle"></param>
        /// <param name="ns"></param>
        public static void ParseReferenceXml(this CarGroupDto carGroup, XElement ReferenceElement, XElement xVehicle, XNamespace ns = null)
        {
            var AirConditionInd = XmlHelpler.ParseValue(xVehicle, "AirConditionInd");//是否有空调
            var automatic = XmlHelpler.ParseValue(xVehicle, "TransmissionType").ToLower();//是否为自动挡

            if (ReferenceElement != null)
            {
                var ReferenceType = XmlHelpler.ParseValue(ReferenceElement, "Type");  // Features
                var ReferenceID = XmlHelpler.ParseValue(ReferenceElement, "ID");
                if (ReferenceType == "Features")
                {
                    carGroup.Feature = new CarFeatureDto(ReferenceID);
                }
            }
            else
            {
                carGroup.Feature = new CarFeatureDto("");
            }

            if (automatic == "automatic")
            {
                carGroup.Feature.IsAutomatic = true;
            }
            else if (automatic == "manual")
            {
                carGroup.Feature.IsAutomatic = false;
            }

            if (AirConditionInd != null)
            {
                carGroup.Feature.HasAirConditioning = AirConditionInd.Contains("true");
            }
        }
    }
}
